<template>
  <div class="app-container" id="container"  >
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="70px" class = "top-input">
<!--      <el-form-item label="围栏名称" prop="fenceName" >-->
<!--        <el-input-->
<!--          v-model="queryParams.fenceName"-->
<!--          placeholder="请输围栏名称"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->

      <el-form-item prop="cityCode" label="城市">
        <el-select v-model="queryParams.cityCode" placeholder="请选择城市" @change = "getDistrict" >
          <el-option
            v-for="dict in cityOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item  label="行政区" prop="adcode" >
        <el-select v-model="queryParams.adcode" placeholder="请选择行政区"  @change="getLocalDistrict" >
          <el-option
            v-for="district in districtOptions"
            :key="district.adcode"
            :label="district.name"
            :value="district.adcode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item  label="乡镇区域" prop="districtId" >
        <el-select v-model="queryParams.districtId" placeholder="请选择围栏区域" >
          <el-option
            v-for="district in localDistrictOptions"
            :key="district.id"
            :label="district.districtName"
            :value="district.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery(0)">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8 top-btn" >
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          v-if="!openIsAdd"
          @click="handleOpenAdd"
        >添加</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-i  con-save"
          size="mini"
          @click="handleSave"
          v-if="openIsAdd"
        >保存</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-i  con-save"
          size="mini"
          @click="handleReset"
          v-if="openIsAdd"
        >重新绘制</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-save"
          size="mini"
          @click="handleClose"
          v-if="!openIsClose"
        >退出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-i  con-save"
          size="mini"
          @click="handleCheckAddress"
        >{{checkInputName}}</el-button>
      </el-col>
      <el-col :span="1.5" >
        <el-input size="mini" v-if="checkInput" id="tipinput" placeholder="请输入地址" v-model="form.address" @focus="bindInput"/>
      </el-col>
    </el-row>

    <div id = "dialog">
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item  label="围栏名称" prop="fenceName" v-if="title !=='新增围栏'" >
            <el-input v-model="form.fenceName" placeholder="请输入围栏名称" />
          </el-form-item>
          <el-form-item label="城市" prop="cityCode" v-if="title == '新增围栏'" >
              <el-select v-model="form.cityCode" placeholder="请选择城市" @change="getDistrict">
                <el-option
                  v-for="dict in cityOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
          </el-form-item>
          <el-form-item label="区县" prop="adcode" v-if="title == '新增围栏'" >
            <el-select v-model="form.adcode" placeholder="请选择区县" @change="getLocalDistrict">
              <el-option
                v-for="district in districtOptions"
                :key="district.adcode"
                :label="district.name"
                :value="district.adcode"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item  label="乡镇区域" prop="districtId" v-if="title == '新增围栏'" >
            <el-select v-model="form.districtId" placeholder="请选择乡镇区域" @change="getDistrictRadius">
              <el-option
                v-for="district in localDistrictOptions"
                :key="district.id"
                :label="district.districtName"
                :value="district.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!--<el-form-item  label="区域半径" prop="districtRadius" >
            <el-input  v-model="form.districtRadius" disabled="disabled" />
          </el-form-item>-->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" v-if="title == '新增围栏'" @click="handleSaveFence">保存</el-button>
          <el-button type="primary" v-if="title == '编辑围栏名称'" @click="handleUpDataFence">保存</el-button>
          <el-button type="primary" v-if="title == '新增围栏'" @click="handleAdd">绘制</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>

  </div>
</template>
<style>
  html, body, #container {
    width: 100%;
    margin: 0;
  }
  .top-btn {
    position: fixed;
    margin-bottom: 7px;
    z-index: 999;
    top: 150px
  }

  .top-input {
    position: fixed;
    margin-bottom: 7px;
    z-index: 999;
  }

</style>
<script>
  import AMapLoader from '@amap/amap-jsapi-loader';
  import $ from 'jquery';
    import { listFence,saveCache,saveFenceByQy,delFence,genFencePoints,checkFence,updateFence ,fenceLocation, upDataFenceName } from "@/api/integration/gaode";
  import {
    getDistrictByCity,
    getLocalDistrictByCity,
    getTowsPopByRole,
    listDistrict,
    resetTownDistrict
  } from "@/api/integration/district";
  import user from "@/store/modules/user";

  var map;
  var polyEditor;
  var rightClickPolygon = null;
  var infoWindow;
  var contextMenu;
  var mouseTool;
  var autoOptions
  var opType;
  var tempFence = {};
  var fencePolygons = [];
  var districtPolygons = [];
  var districtPolygon = null;
  var marker;
  var contextXZMenu;
export default {
  name: "GaodeAz",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 显示搜索条件
      showSearch: true,
      // 弹出层标题
      title: "",
      /** 是否显示地址框 */
      checkInput: false,
      checkInputName : "地址检查",
      fenceList:[],
      districtList: [],
      cityOptions: [],
      districtOptions: [],
      localDistrictOptions: [],
      // 是否显示弹出层
      open: false,
      userPop: null,
      openIsAdd: false,
      openIsSave:true,
      openIsClose:true,
      // 查询参数
      queryParams: {
        // cityCode : '0791'
      },
      // 围栏表单参数
      form: {},
      // 区域围栏参数
      districtForm: {},
      // 表单校验
      rules: {
        cityCode: [
          { required: true, message: "请选择城市", trigger: "blur" }
        ],
        adcode: [
          { required: true, message: "请选择区县", trigger: "blur" }
        ],
        districtId: [
          { required: true, message: "请选择乡镇区域", trigger: "blur" }
        ],
        address: [
          { required: true, message: "请输入地址", trigger: "blur" }
        ],
        /*fenceType: [
          { required: true, message: "请选择围栏类型", trigger: "blur" }
        ]*/
      }
    };
  },
  created() {
    getTowsPopByRole().then(response => {
      this.userPop = response.data;
    }).then(() => {
      this.init();
    })
    this.getDicts("city").then(response => {
      this.cityOptions = response.data;
    });

  },
  methods: {
    init(){
      AMapLoader.load({
        "key": "3fa060bd1711d61ee47bb8983d7b1101",              // 申请好的Web端开发者Key，首次调用 load 时必填
        "version": "2.0",   // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        "plugins": ['AMap.Scale','AMap.ToolBar','AMap.PolygonEditor','AMap.PolylineEditor','AMap.CircleMarker','AMap.MouseTool',"AMap.DistrictSearch","AMap.GeometryUtil","AMap.PlaceSearch","AMap.AutoComplete"],           // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then((AMap)=>{
        map = new AMap.Map('container', {
          resizeEnable: true,
          /*center: [116.471354, 39.994257],*/
          zoom: 8,
          showIndoorMap: false
        });
        infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -30)});
        contextMenu = new AMap.ContextMenu();
        contextMenu.addItem("修改名称", this.handleOpenEdit, 0);
        contextMenu.addItem("修改坐标", this.handleUpdate, 1);
        // contextMenu.addItem("删除", this.handleDelete, 2);
        map.addControl(new AMap.Scale());
        map.addControl(new AMap.ToolBar());
        mouseTool = new AMap.MouseTool(map);
        map.setCity("南昌");
        this.getDistrictList();
        this.getFenceList();
        polyEditor = new AMap.PolygonEditor(map);
        polyEditor.on('add', this.addCache);
        polyEditor.on('end', this.updateCache)
        $("#container").css("height",(document.body.offsetHeight)-85+"px")
      }).catch(e => {
          console.log(e);
      })
    },
    updateCache(data){
      var polygon = data.target;
      if(opType=="reset"){
        map.remove(polygon);
      }
      if(opType == "saveCache"){
        //将地图页面上的围栏保存到数据库中
        if(polygon==null){
          this.msgError("无数据可以保存");
          return;
        }
        var path = polygon.getPath();
        //检查围栏坐标点的移入动作是否移入到了其他围栏中移入了则将2边界重合
        var points = "";
        for(var i=0;i<path.length;i++){
          if (i < path.length - 1) {
            points = points+path[i].getLng()+","+path[i].getLat()+";"
          } else {
            points = points+path[i].getLng()+","+path[i].getLat();
          }
        }
        tempFence.fencePoints = points;
        tempFence.pointList = path;
        if(districtPolygon!=null){
          tempFence.districtPointList = districtPolygon.getPath();
        }
        saveCache(tempFence).then(response => {
          if(response.data.code==200){
            this.handleQuery();
            this.msgSuccess("保存成功");
          }else{
            this.msgError(response.data.message);
            polyEditor.setTarget(polygon);
            polyEditor.open();
            opType = '';
          }

        });
      }
    },
    //切割区域生成围栏坐标
    addCache(data){
        //当前围栏对象
        var polygon = data.target;
        //当前围栏坐标
        var path = polygon.getPath();
        var clockwise = AMap.GeometryUtil.isClockwise(path);
        if(!clockwise){
          this.$message({
            showClose: true,
            message: '请顺时针方向绘制围栏, 警告',
            type: 'warning'
          });
          opType = "reset";
          polyEditor.setTarget();
        }else {
          var data = {"paths":path,"districtPaths":districtPolygon.getPath()}
          genFencePoints(data).then(response => {
            if(response.code==200){
              var newPaths = response.data;
              map.remove(polygon);
              var polygon2 = new AMap.Polygon({
                strokeWeight: 2,
                path: newPaths,
                fillOpacity: 0.4,
                fillColor: '#199cff',
                strokeColor: '#13ffff',
                extData:{
                  fence: tempFence
                }
              });
              polyEditor.setTarget(polygon2);
              map.add(polygon2);
              polyEditor.open();
            }else{
              opType = "reset";
              polyEditor.setTarget();
              this.$message({
                showClose: true,
                message: response.msg+', 警告',
                type: 'warning'
              });
            }
          });
        }

    },
    initQyPolygon(district) {
      if(district.districtPoints!=""){
        var str = district.districtPoints.split(";");
        var path = [];
        for(var i=0;i<str.length;i++) {
          var point = str[i].split(",");
          var zb = new AMap.LngLat(point[0], point[1])
          path.push(zb);
        }
        //查询可分配围栏的区域坐标
        var polygon = new AMap.Polygon({
          path: path,
          fillColor: '#ccebc5',
          strokeOpacity: 1,
          fillOpacity: 0.5,
          strokeColor: '#2b8cbe',
          strokeWeight: 1,
          strokeStyle: 'dashed',
          strokeDasharray: [5, 5],
          extData: {
            districtId: district.id,
            district: district
          }
        });
        if(opType === "query"){
          map.setFitView(
            polygon,  // 覆盖物数组
            false,  // 动画过渡到制定位置
            [60, 60, 60, 60],  // 周围边距，上、下、左、右
            14,  // 最大 zoom 级别
          );
        }
        polygon.content = '乡镇名称：'+district.districtName;
        contextXZMenu = new AMap.ContextMenu();
        contextXZMenu.addItem("重置乡镇", this.resetTown, 0);
        polygon.on('rightclick', this.rightClickTarget)
        polygon.on('click', this.closeMenu);
        map.add(polygon)
        districtPolygons.push(polygon);
      }
    },
    rightClickTarget(e){
      if(!this.openIsAdd){
        rightClickPolygon = e.target;
        contextXZMenu.open(map, e.lnglat);
      }
    },
    closeMenu(){
      contextMenu.close();
      contextXZMenu.close();
    },
    resetTown(){
      contextMenu.close();
      contextXZMenu.close();
      var town = rightClickPolygon.getExtData().district;
      this.$confirm('是否重置名称为' + town.districtName + '的数据项?该操作将会重置子区域', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        if (town.districtLevel === 3) {
          return resetTownDistrict(town);
        }
      }).then(() => {
        this.handleQuery();
        this.msgSuccess("重置成功");
      })
    },
    initFencePolygon(fence){
      var str = fence.fencePoints.split(";");
      var path = [];
      for(var i=0;i<str.length;i++) {
        var point = str[i].split(",");
        path.push(new AMap.LngLat(point[0], point[1]));
      }
      var polygon = new AMap.Polygon({
        strokeWeight: 2,
        path: path,
        fillOpacity: 0.4,
        fillColor: fence.fenceColor,
        strokeColor: '#0091ea',
        extData:{
          fence: fence
        }
      });
      map.add(polygon);
      fencePolygons.push(polygon);
      polygon.content = '围栏名称：'+fence.fenceName;
      polygon.on('click', this.polygonClick);
      polygon.on('rightclick', function (e) {
        infoWindow.close();
        if(!polyEditor.getTarget()){
          rightClickPolygon = e.target;
          contextMenu.open(map, e.lnglat);
        }
      });
    },
    polygonClick(e) {
      infoWindow.setContent(e.target.content);
      infoWindow.open(map, e.lnglat);
      contextMenu.close();
    },

    //查询初始化区域
    getDistrictList(){
      districtPolygons = [];
      this.queryParams.districtLevel = 3;
      listDistrict(this.queryParams).then(response => {
        this.districtList = response.data;
        for(var i=0;i<this.districtList.length;i++){
          var table = this.districtList[i];
          this.initQyPolygon(table);
        }
        opType = '';
      });

    },
    getFenceList(){
      fencePolygons = [];
      listFence(this.queryParams).then(response => {
        this.fenceList = response.data;
        for(var i=0;i<this.fenceList.length;i++){
          var table = this.fenceList[i];
          this.initFencePolygon(table);
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.open = false;
      this.resetForm("form");
    },
    handleReset(){
      if(opType != "saveCache"){
        opType = "reset";
        polyEditor.setTarget();
        polyEditor.open();
      }

    },
    /** 搜索按钮操作 */
    handleQuery(isRest) {
      if(isRest === 0){
        opType = "query";
      }
      tempFence = {};
      districtPolygon = null;
      for (var i = 0, l = districtPolygons.length; i < l; i++) {
        map.remove(districtPolygons[i]);
      }
      map.clearMap();
      this.getDistrictList();
      this.getFenceList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleClose(){
      if(polyEditor.getTarget()){
        var polygon = polyEditor.getTarget();
        map.setFitView(
          polygon,  // 覆盖物数组
          false,  // 动画过渡到制定位置
          [60, 60, 60, 60],  // 周围边距，上、下、左、右
          14,  // 最大 zoom 级别
        );
        var fence = polygon.getExtData().fence;
        this.$confirm('围栏：【' + fence.fenceName + '】未保存，确定要放弃编辑?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() =>{
          this.openIsClose = true;
          this.openIsAdd = false;
          this.openIsSave = true;
          opType = "";
          polyEditor.setTarget();
          polyEditor.close();//关闭编辑*/
          this.handleQuery();
          $(".top-input").show();
        }).catch(() => {
            console.log("cancel");
        });
      }else{
        this.openIsClose = true;
        this.openIsAdd = false;
        this.openIsSave = true;
        opType = "";
        polyEditor.close();//关闭编辑*/
        this.handleQuery();
        $(".top-input").show();
      }
    },
    handleOpenAdd(){
      this.reset();
      contextMenu.close();
      this.open = true;
      this.title = "新增围栏";
    },
    handleOpenEdit(){
      this.reset();
      contextMenu.close();
      this.form = rightClickPolygon.getExtData().fence;
      this.open = true;
      this.title = "编辑围栏名称";
    },
    submitEdit(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateFence(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.handleQuery();
            });
          }
        }
      });
    },
    /** 添加按钮操作 */
    handleAdd() {//校验表单数据
      this.$refs["form"].validate(valid => {
        if (valid) {
          districtPolygons.forEach(item =>{
            map.remove(item);
            //获取当前选择的区域
            if(this.form.districtId == item.getExtData().districtId ){
              districtPolygon = item;
              map.add(districtPolygon);
              map.setFitView(districtPolygon);
            }
          })
          if (districtPolygon == null) {
            this.msgError("该区域围栏已建满，无可建区域");
            return;
          }
          var paths = districtPolygon.getPath();
          paths.forEach(function(path){
            var circleMarker = new AMap.CircleMarker({
              center:[path.getLng(), path.getLat()],
              radius:4,//3D视图下，CircleMarker半径不要超过64px
              strokeColor:'white',
              strokeWeight:2,
              strokeOpacity:0.5,
              fillColor:'rgba(0,0,255,1)',
              fillOpacity:0.5,
              zIndex:10,
              bubble:true,
              cursor:'pointer',
              clickable: true
            })
            circleMarker.setMap(map)
          })
          map.add(districtPolygon);
          polyEditor.addAdsorbPolygons(districtPolygon);
          //检查名称是否重复
          // checkFence(this.form).then(response=>{
          //   if(response.code == 200){
          //
          //   }else{
          //     this.msgError(response.msg)
          //   }
          // })
          this.open = false;
          tempFence = this.form;
          $(".top-input").hide();
          this.openIsAdd = true;
          this.openIsClose = false;
          this.openIsSave = false;
          polyEditor.setTarget();
          polyEditor.open();//开启编辑
        }
      });

    },
    /** 修改按钮操作，进入编辑状态 */
    handleUpdate() {
      contextMenu.close();
      tempFence = rightClickPolygon.getExtData().fence;
      opType = "";
      this.openIsSave = false;
      this.openIsAdd = true;
      this.openIsClose = false;
      $(".top-input").hide();
      polyEditor.setTarget(rightClickPolygon);
      polyEditor.open();
    },
    handleSave(){
      this.openIsAdd = false;
      opType = "saveCache";
      polyEditor.setTarget();
    },
    handleSaveFence(){
      this.$refs["form"].validate(valid => {
        if(valid) {
          saveFenceByQy(this.form).then(response=>{
            if(response.data.code==200){
              this.handleQuery();
              this.msgSuccess("保存成功")
              this.reset();
            }else{
              this.msgError(response.data.message)
            }
          })
        }
      })
    },
    handleUpDataFence(){
      this.$refs["form"].validate(valid => {
        if(valid) {
          upDataFenceName(this.form).then(response => {
            if (response.code == 200) {
              this.handleQuery();
              this.msgSuccess("保存成功")
              this.reset();
              this.handleQuery();
            } else {
              this.msgError(response.message)
            }
          })
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete() {
      contextMenu.close();
      var fence = rightClickPolygon.getExtData().fence;
      var data = {'name': fence.fenceName,'code': fence.fenceCode};
      this.$confirm('是否确认删除名称为' + fence.fenceName + '的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delFence(data);
      }).then(() => {
        this.handleQuery();
        this.msgSuccess("删除成功");
      })
    },
    /** 查询地址按钮 */
    handleCheckAddress(){
      if(this.checkInput == true){
        this.checkInput = false;
        this.checkInputName = "地址检查";
        this.deleteMarker()
        this.form.address = null;
      }else if(this.checkInput == false){
        this.checkInput = true;
        this.checkInputName = "关闭搜索框";
        autoOptions = {
          input: "tipinput"
        };
      }
    },
    bindInput(){
      if($("#tipinput").length>0)
      {
        var auto = new AMap.AutoComplete(autoOptions);
        var placeSearch = new AMap.PlaceSearch({
          map: map
        });  //构造地点查询类
        auto.on("select",this.selectAddress);//注册监听，当选中某条记录时会触发
      }
    },
    selectAddress(e) {
      console.log(e)
      var data = {};
      data.address = e.poi.district + e.poi.name;
      data.addressPop = this.userPop[0];
      fenceLocation(data).then(response =>{
        this.msgSuccess( "围栏名为:" + response.data.fenceName)
      })
      marker = new AMap.Marker({
        map: map,
        icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
        position: [e.poi.location.lng, e.poi.location.lat]
      });
      marker.setMap(map);
      marker.on('click', this.deleteMarker);
      map.setZoomAndCenter(16, [e.poi.location.lng, e.poi.location.lat]);
    },
    deleteMarker(){
      if(marker !== null){
        marker.setMap(null);
        marker = null;
      }
    },
    getDistrict(value){
      var data ={};
      data.cityCode = value;
      this.cityOptions.forEach(item =>{
        if(value==item.dictValue){
          data.city = item.dictLabel;
          this.form.city = item.dictLabel;
        }
      })
      getDistrictByCity(data).then(response=>{
        this.districtOptions = response.data;
      })
    },
    getLocalDistrict(value){
      var data ={};
      data.adcode = value;
      data.cityCode = this.form.cityCode;
      data.districtLevel = 3;
      getLocalDistrictByCity(data).then(response=>{
        this.localDistrictOptions = response.data;
      })
    },
    getDistrictRadius(value){
      this.localDistrictOptions.forEach(item=>{
        if(item.id==value){
          this.form.districtRadius = item.districtRadius;
        }
      })
    }

  }
};
</script>
